<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML5商业化开发细节</title>
    <link rel="stylesheet" href="./common.css">
</head>
<body>
    <div class="keys">
        <div class="key" data-key="65">
            <div>A</div>
            <span class="sound">clap</span>
        </div>
        <div class="key" data-key="83">
            <div>S</div>
            <span class="sound">hihat</span>
        </div>
        <div class="key" data-key="68">
            <div>D</div>
            <span class="sound">kick</span>
        </div>
        <div class="key" data-key="70">
            <div>F</div>
            <span class="sound">openhat</span>
        </div>
        <div class="key" data-key="71">
            <div>G</div>
            <span class="sound">boom</span>
        </div>
        <div class="key" data-key="72">
            <div>H</div>
            <span class="sound">ride</span>
        </div>
        <div class="key" data-key="74">
            <div>J</div>
            <span class="sound">snare</span>
        </div>
        <div class="key" data-key="75">
            <div>K</div>
            <span class="sound">tom</span>
        </div>
        <div class="key" data-key="76">
            <div>L</div>
            <span class="sound">tink</span>
        </div>
    </div>
    <audio src="./sounds/clap.wav" data-key="65"></audio>
    <audio src="./sounds/hihat.wav" data-key="83"></audio>
    <audio src="./sounds/kick.wav" data-key="68"></audio>
    <audio src="./sounds/openhat.wav" data-key="70"></audio>
    <audio src="./sounds/boom.wav" data-key="71"></audio>
    <audio src="./sounds/ride.wav" data-key="72"></audio>
    <audio src="./sounds/snare.wav" data-key="74"></audio>
    <audio src="./sounds/tom.wav" data-key="75"></audio>
    <audio src="./sounds/tink.wav" data-key="76"></audio>
<script>
function playSound(e){
    // console.log(e.keyCode)
    const keyCode = e.keyCode
    //标签的数据属性
    const key = document.querySelector(
        `.key[data-key="${keyCode}"]`
    )
    if (key) {
        key.classList.add('playing')
    }


    const audio = document.querySelector(
        `audio[data-key="${keyCode}"]`
    )
    if(audio) {
        audio.currentTime = 0
        audio.play()
    }

    // setTimeout(() => {
    //     key.classList.remove('playing')
    // }, 100);
}
const keys = Array.from(document.querySelectorAll('.key'))
keys.forEach(key => {
    //事件一定要一个一个元素的加
    key.addEventListener('transitionend',function(e){
        // console.log(e)
        // console.log(e.propertyName)
        if(e.propertyName !== 'transform') return
        this.classList.remove('playing')
    })
})
window.addEventListener('keydown',playSound)
</script>
</body>
</html>